package com.example.demo09redisbloom.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.scripting.support.ResourceScriptSource;

import java.util.List;

@Configuration
public class RedisConfig {

    @Bean
    RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
        redisTemplate.setConnectionFactory(connectionFactory);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

    // BF.ADD 指令
    @Bean
    public DefaultRedisScript<Boolean> bloomAddRedisScript() {
        DefaultRedisScript<Boolean> bloomAddOne = new DefaultRedisScript<>();
        bloomAddOne.setScriptSource(new ResourceScriptSource(new ClassPathResource("bloomFilterAdd.lua")));
        bloomAddOne.setResultType(Boolean.class);
        return bloomAddOne;
    }

    // BF.MADD 指令
    @Bean
    public DefaultRedisScript<List> bloomMAddRedisScript() {
        DefaultRedisScript<List> bloomAddOne = new DefaultRedisScript<>();
        bloomAddOne.setScriptSource(new ResourceScriptSource(new ClassPathResource("bloomFilterMAdd.lua")));
        bloomAddOne.setResultType(List.class);
        return bloomAddOne;
    }

    // BF.EXISTS 指令
    @Bean
    public DefaultRedisScript<Boolean> bloomExistRedisScript() {
        DefaultRedisScript<Boolean> bloomExistOne = new DefaultRedisScript<>();
        bloomExistOne.setScriptSource(new ResourceScriptSource(new ClassPathResource("bloomFilterExists.lua")));
        bloomExistOne.setResultType(Boolean.class);
        return bloomExistOne;
    }
}
